<?php
namespace app\user\controller;

use app\user\model\Applet as AppletModel;
use app\user\model\Template as TemplateModel;
use app\user\model\User as UserModel;
use think\facade\View;

/**
 * 小程序管理
 */
class Applet extends Controller
{
	/**
     * 获取列表
     */
    public function index()
    {
		$model = new AppletModel;
        $list = $model->getList(0,$this->user_id);
        return View::fetch('index', compact('list'));
    }

    /**
     * 添加
     */
    public function add()
    {
        if (!$this->request->isAjax()) {
            $model = new TemplateModel;
			$list = $model->getList($this->agent_id);
            $user = UserModel::getUser(['user_id' => $this->user_id]);
            $money = $user['money'];
            return View::fetch('add',compact('list','money'));
        }
        $model = new AppletModel;
		$data = $this->postData('data');
		$data['user_id'] = $this->user_id;
		$data['agent_id'] = $this->agent_id;
        if ($model->add($data)) {
            return $this->renderSuccess('创建成功', url('applet/index'));
        }
        $error = $model->getError() ?: '创建失败';
        return $this->renderError($error);
    }

    /**
     * 删除
     */
    public function delete($id)
    {
        $model = new AppletModel;
         if ($model->remove($id)) {
			return $this->renderSuccess('删除成功');
        }
		$error = $model->getError() ?: '删除失败';
		return $this->renderError($error);
    }

    /**
     * 一键登录
     */
    public function oneKey($id)
    {
        // 小程序详情
		$model = AppletModel::get($id);
		if ($url = $model->login()) {
			return redirect($url);
		}
        return $this->renderError('登录失败');	
    }

    /**
     * 升级续费列表
     */
    public function status($id)
    {
		$applet = AppletModel::get($id);
		$template = TemplateModel::getAppType($applet['app_type'],$this->agent_id);
		if (!$this->request->isAjax()) {
            $user = UserModel::getUser(['user_id' => $this->user_id]);
            $money = $user['money'];
			return View::fetch('upgrade',compact('applet','template','money'));
        }
		$data = $this->postData('data');
		// 创建订单
		if($applet->upgrade($data,$template)) {
			return $this->renderSuccess('续费成功', url('applet/index'));
        }
        $error = $model->getError() ?: '续费失败';
        return $this->renderError($error);
    }
}
